/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package cz.mzk.oai.metadataRepository.harvest.tei.svnManager;

import cz.mzk.oai.metadataRepository.metadata.DateStamp;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.joda.time.DateTime;
import org.joda.time.DateTimeUtils;
import org.tmatesoft.svn.core.SVNException;
import org.tmatesoft.svn.core.io.SVNRepository;

/**
 *
 * @author Martin Řehánek (rehan at mzk.cz)
 */
public class GetSortedRevisionsAction extends Action {

    public GetSortedRevisionsAction(SVNRepository repository) {
        super(repository);
    }

    public List<Long> run(DateStamp from, DateStamp until) throws SVNException {
        long fromRevision = getFirstRevision(from);
        long toRevision = getLastRevision(until);
        if (fromRevision > toRevision) {
            Logger.getLogger(GetSortedRevisionsAction.class.getName()).log(Level.SEVERE, "{0} is after {1}", new Object[]{from, until});
            return Collections.<Long>emptyList();
        }
        return createRevisionList(fromRevision, toRevision);
    }

    private long getFirstRevision(DateStamp from) throws SVNException {
        if (from == null) {
            return 1;
        } else {
            return getRevision(from);
        }
    }

    private long getRevision(DateStamp dateStamp) throws SVNException {
        Date date = toDate(dateStamp);
        return repository.getDatedRevision(date);
    }

    private Date toDate(DateStamp dateStamp) {
        DateTime dateTime = dateStamp.getDateTime();
        long millis = DateTimeUtils.getInstantMillis(dateTime);
        Date date = new Date(millis);
        return date;
    }

    private long getLastRevision(DateStamp until) throws SVNException {
        if (until == null) {
            return repository.getLatestRevision();
        } else {
            return getRevision(until);
        }
    }

    private List<Long> createRevisionList(long firstRevision, long latestRevision) {
        if (firstRevision > latestRevision) {
            throw new IllegalArgumentException("firstRevision > latestRevision");
        }
        List<Long> result = new ArrayList<Long>();
        for (long i = firstRevision; i <= latestRevision; i++) {
            result.add(Long.valueOf(i));
        }
        return result;
    }
}
